package drrr.controller;

import com.opensymphony.xwork2.ActionContext;
import drrr.common.SpringContext;
import drrr.orm.RoomEntity;
import drrr.orm.RoomMemberEntity;
import drrr.orm.UserEntity;
import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.util.Map;

/**
 * Created by lirance on 15/5/16.
 */

// 创建房间
public class CreateRoom extends BaseAction {
    private String roomname;
    private String membernum;
    private String roomtype;

    public String getRoomname() {
        return roomname;
    }

    public void setRoomname(String roomname) {
        this.roomname = roomname;
    }

    public String getMembernum() {
        return membernum;
    }

    public void setMembernum(String membernum) {
        this.membernum = membernum;
    }

    public String getRoomtype() {
        return roomtype;
    }

    public void setRoomtype(String roomtype) {
        this.roomtype = roomtype;
    }

    @Override
    public String execute() throws Exception {
        RoomEntity roomEntity = new RoomEntity();
        UserEntity user = ((UserEntity) ServletActionContext.getContext().getSession().get("user"));
        int ow = user.getId();
        roomEntity.setMembernum(new Integer(getMembernum()));
        roomEntity.setRoomname(getRoomname());
        roomEntity.setOwner(ow);
        roomEntity.setType(new Integer(getRoomtype()));
        getAllService().getRoomService().insert(roomEntity);


        //得到插入表的房间的id
        SessionFactory sessionFactory = (SessionFactory) SpringContext.getBean("sessionFactory");
        Session session1 = sessionFactory.openSession();
        int creatRoomId = (int)(session1.createSQLQuery("SELECT id FROM room WHERE (roomname='" + roomEntity.getRoomname() + "' AND owner=" + roomEntity.getOwner() + ")").list().get(0));
        session1.close();


        //设定房间在线人数.
        String roomOnline=String.format("roomOnline%s",creatRoomId+"");
        ActionContext.getContext().getApplication().put(roomOnline, 1);
        roomEntity.setId(creatRoomId);

        Map<String, Object> session = ServletActionContext.getContext().getSession();
        session.put("room", roomEntity); //设定房间
        session.put("creatRoomId",creatRoomId);//创建的房间id

        int memberid = ((UserEntity) session.get("user")).getId();
        RoomMemberEntity roomMemberEntity = new RoomMemberEntity();
        roomMemberEntity.setRoomId(creatRoomId);
        roomMemberEntity.setMemberId(memberid);
        getAllService().getRoomMemberService().insert(roomMemberEntity);
        session.put("member", roomMemberEntity);
        if (user != null)
            return SUCCESS;
        else return ERROR;
    }


}

